<template>
	<view class="echarts-container" :data-id="id" :change:data-id="echarts.updateId" :option="option"
		:change:option="echarts.updateOption">
		<view class="chart-box" :id="id"></view>
	</view>
</template>

<script>
	export default {
		props: ['option'],
		data() {
			return {
				id: 'echarts-' + Math.random()
			}
		}
	}
</script>

<script module="echarts" lang="renderjs">
	let myChart

	export default {
		data() {
			return {
				idR: null,
				optionR: {}
			}
		},
		mounted() {
			if (window.echarts) {
				this.initEcharts()
			} else {
				const script = document.createElement('script')
				script.src = 'static/echarts.min.js'
				script.onload = this.initEcharts.bind(this)
				document.head.appendChild(script)
			}
		},
		methods: {
			initEcharts() {
				if (!window.echarts) return
				
				myChart = echarts.init(document.getElementById(this.idR))
				myChart.clear()
				myChart.setOption(this.optionR, {
					notMerge: true
				})
			},
			updateId(newValue, oldValue, ownerInstance, instance) {
				// id在根元素，会获取不到元素
				this.idR = newValue
			},
			updateOption(newValue, oldValue, ownerInstance, instance) {
				this.optionR = newValue
				 // renderjs同页面多个图表echart实例会冲突，重新创建实例
				this.initEcharts()
			}
		}
	}
</script>

<style scoped>
	.echarts-container {}

	.chart-box {
		width: 100%;
		height: 100%;
	}
</style>